package com.sgb.kjwl.view.ui.fragment.packers;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityPopularWorkersBinding;
import com.sgb.kjwl.model.entity.PopularWorkersEntity;
import com.sgb.kjwl.model.entity.packers.PickResultEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.NumberConstant;
import com.sgb.kjwl.view.ui.adapter.packers.PopularWorkersAdapter;
import com.sgb.kjwl.view.widget.GoodsTypePopWindow4;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.packers.PopularWorkersModel;
import com.sgb.link.entity.PickFilterEntity;
import com.sgb.link.router.PathTeam;
import com.swgk.core.base.model.entity.SelectPopEntity;
import com.swgk.core.customview.ScreenChildTextView;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.interfaces.PopClick;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.weiget.TwoLevelPopWindow;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : younghow
 * @date : 2021/12/3 11:29
 * description:
 */
public class PopularTeamFragment extends AppLazyFragment {

    PopularWorkersModel viewModel;
    private ActivityPopularWorkersBinding binding;
    private PopularWorkersAdapter popularWorkersAdapter;

    /**
     * 工程专项
     */
    private TwoLevelPopWindow<PickFilterEntity> popMajor;
    private PickResultEntity pickResultMajor;
    private PickResultEntity pickResultMajorTwo;
    private PickResultEntity pickResultMajorThree;

    /**
     * 所在区域
     */
    private ThreeLevelAreaWindow popCity;
    private PickResultEntity pickResultProvince;
    private PickResultEntity pickResultCity;
    private PickResultEntity pickResultArea;
    private String mAreaCode, mAreaName;
    private boolean isLoadMore;
    private List<PickFilterEntity<List<PickFilterEntity<List<PickFilterEntity>>>>> workType;
    private GoodsTypePopWindow4 carsTypePopWindow;
    private int typePosition = -1;
    private List<GoodsInfoTypeEntity3> carsTypeData;
    private SelectPopEntity selectPopEntity0;

    public static PopularTeamFragment newInstance() {
        PopularTeamFragment intent = new PopularTeamFragment();
        Bundle bundle = new Bundle();
        intent.setArguments(bundle);
        return intent;
    }

    private void initFilterData(boolean isLoadMore) {
        this.isLoadMore = isLoadMore;
        viewModel.getNewList(pickResultProvince.getNo(), pickResultArea.getNo(), pickResultMajor.getNo(), pickResultMajorTwo.getNo(), pickResultMajorThree.getNo(), "", "", "", "", pickResultCity.getNo(), isLoadMore);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.activity_popular_workers, container, false);
        return binding.getRoot();
    }

    @Override
    protected void initView() {

        binding.setLifecycleOwner(this);
        viewModel = new ViewModelProvider(this).get(PopularWorkersModel.class);

        carsTypeData = new ArrayList<>();

        binding.ivEmploymentAll.setOnClickListener(this);

        setTextButton();
        binding.sct.onSetCallPop(new ScreenChildTextView.ICallPop() {
            @Override
            public void openPop(int position, TextView content, LinearLayout bg, SelectPopEntity entity) {
                if (binding.sct.getSize() == 2){
                    if (position == 0) {
                        showType();
                    } else if (position == 1) {
                        showCityPop();
                    }
                }else if (binding.sct.getSize() == 1){
                    if (position == 0) {
                        showCityPop();
                    }
                }
            }
        });

        if (popularWorkersAdapter == null) {
            popularWorkersAdapter = new PopularWorkersAdapter(getActivity(), null, Glide.with(this));
        }

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        popularWorkersAdapter.setOnItemClick(new AdapterOnItemClick<PopularWorkersEntity>() {
            @Override
            public void onItemClick(PopularWorkersEntity popularWorkersEntity, int position) {
                viewModel.TeamParticulars(popularWorkersEntity.getNo());
            }
        });
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.setAdapter(popularWorkersAdapter);
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initFilterData(false);
            }

            @Override
            public void onLoadMore() {
                initFilterData(true);
            }
        });

        mAreaCode = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_CODE, "");
        mAreaName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_NAME, "");

        pickResultMajor = new PickResultEntity();
        pickResultProvince = new PickResultEntity();
        pickResultCity = new PickResultEntity();
        pickResultArea = new PickResultEntity();
        pickResultMajorTwo = new PickResultEntity();
        pickResultMajorThree = new PickResultEntity();
        pickResultProvince.setNo(mAreaCode);
        pickResultProvince.setName(mAreaName);
        pickResultCity.setNo("");
        pickResultCity.setName("全部");
        pickResultArea.setNo("");
        pickResultArea.setName("全部");

        binding.rvPackerChangeFirstContentTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                carsTypePopWindow.setDefItem(tab.getPosition());
                if (tab.getPosition() != 0) {
                    pickResultMajor.setNo(workType.get(tab.getPosition()).getNo());
                    pickResultMajor.setName(workType.get(tab.getPosition()).getName());
                } else {
                    pickResultMajor.setNo("");
                    pickResultMajor.setName("全部");
                }

                pickResultMajorTwo.clear();
                pickResultMajorThree.clear();
                initFilterData(false);
                if (tab.getPosition() == 0) {
                    binding.sct.removeTextButton(selectPopEntity0);
                    return;
                } else {
                    binding.sct.addTextButton(selectPopEntity0,0);
                    binding.sct.contentSelect("工程专项",false,false,0);
                }

                List<PickFilterEntity<List<PickFilterEntity>>> data = new ArrayList<>(workType.get(tab.getPosition()).getChildren() == null ? new ArrayList<>() : workType.get(tab.getPosition()).getChildren());
                List<PickFilterEntity> oneLevelData = new ArrayList<>();
                data.add(0,new PickFilterEntity("", "全部"));
                List<List<PickFilterEntity>> twoLevelData = new ArrayList<>();
                for (PickFilterEntity<List<PickFilterEntity>> datum : data) {
                    oneLevelData.add(datum);
                    List<PickFilterEntity> oneLevel = new ArrayList<>(datum.getChildren() == null ? new ArrayList<>() : datum.getChildren());
                    oneLevel.add(0, new PickFilterEntity("", "全部"));
                    twoLevelData.add(oneLevel);
                }

                popMajor = new TwoLevelPopWindow<>(getContext());
                popMajor.setBgView(binding.grayLayout);
                popMajor.setPopClick(new PopClick<PickFilterEntity>() {
                    @Override
                    public void reset() {
                        pickResultMajorTwo.clear();
                        pickResultMajorThree.clear();
                        binding.sct.contentSelect("工程专项",false,false,0);
                        initFilterData(false);
                    }

                    @Override
                    public void sure(int provincePosition, int cityPosition, PickFilterEntity provinceEntity, PickFilterEntity cityEntity) {
                        if (provinceEntity != null) {
                            pickResultMajorTwo.setNo(provinceEntity.getNo());
                            pickResultMajorTwo.setName(provinceEntity.getName());
                        } else {
                            pickResultMajorTwo.setNo("");
                            pickResultMajorTwo.setName("全部");
                        }

                        if (cityEntity != null) {
                            pickResultMajorThree.setNo(cityEntity.getNo());
                            pickResultMajorThree.setName(cityEntity.getName());
                        } else {
                            pickResultMajorThree.setNo("");
                            pickResultMajorThree.setName("全部");
                        }

                        if (TextUtils.equals("全部", pickResultMajorThree.getName())) {
                            if (TextUtils.equals("全部", pickResultMajorTwo.getName())){
                                binding.sct.contentSelect("工程专项",false,false,0);
                            }else {
                                binding.sct.contentSelect(pickResultMajorTwo.getName(), true, false, 0);
                            }
                        } else {
                            binding.sct.contentSelect(pickResultMajorThree.getName(),true,false,0);
                        }
                        initFilterData(false);
                    }
                });

                popMajor.setLinkData(oneLevelData, twoLevelData);
                popMajor.setOnDismissListener(() -> binding.sct.contentSelect(!"工程专项".equals(binding.sct.getName(0)),false,0));
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        carsTypePopWindow = new GoodsTypePopWindow4(getActivity());
        carsTypePopWindow.setBgView(binding.grayLayout);
        carsTypePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
                GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) type;
                typePosition = (int) key2;
                pickResultMajor.setNo(entity.getNo());
                if (typePosition != 0){
                    binding.sct.addTextButton(selectPopEntity0,0);
                }
                binding.rvPackerChangeFirstContentTitle.postDelayed(() -> binding.rvPackerChangeFirstContentTitle.getTabAt(typePosition).select(), 100);
                initFilterData(false);
            }
        });
        carsTypePopWindow.setOnDismissListener(() -> binding.ivEmploymentAll.setImageResource(R.mipmap.btn_expand_team_employment));

        initLiveData();
    }

    private void initLiveData() {

        viewModel.loading.observe(getViewLifecycleOwner(), aBoolean -> DialogHelper.showProgressDialog(getContext(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false));

        viewModel.popularList.observe(getViewLifecycleOwner(), list -> {
            if (isLoadMore) {
                binding.recyclerView.loadMoreComplete();
                if (list != null && list.size() > 0) {
                    popularWorkersAdapter.addDatas(list);
                }
                binding.recyclerView.setNoMore(list.size() < 10);
            } else {
                binding.recyclerView.refreshComplete();
                if (list != null && list.size() > 0) {
                    binding.emptyView.setVisibility(View.GONE);
                    popularWorkersAdapter.setDatas(list);
                    binding.recyclerView.smoothScrollToPosition(0);
                } else {
                    popularWorkersAdapter.clearDatas();
                    binding.emptyView.setVisibility(View.VISIBLE);
                }
            }
        });

        viewModel.categoryType.observe(getViewLifecycleOwner(), pickSelectEntities -> {
            workType = pickSelectEntities;
            for (PickFilterEntity<List<PickFilterEntity<List<PickFilterEntity>>>> pickSelectEntity : pickSelectEntities) {
                GoodsInfoTypeEntity3 info = new GoodsInfoTypeEntity3();
                info.setName(pickSelectEntity.getName());
                info.setNo(pickSelectEntity.getNo());
                carsTypeData.add(info);
                binding.rvPackerChangeFirstContentTitle.addTab(binding.rvPackerChangeFirstContentTitle.newTab().setText(pickSelectEntity.getName()));
            }
        });


        viewModel.urlStr.observe(getViewLifecycleOwner(), s -> {
            String[] split = s.split("----");
            com.swgk.core.common.utils.ActivityJump.startActivity(PathTeam.TeamDetailActivity, Pair.create("no", split[1]), Pair.create("url", split[0]));
        });

        viewModel.cityList.observe(getViewLifecycleOwner(), new Observer<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>() {
            @Override
            public void onChanged(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntities) {
                if (popCity == null) {
                    popCity = new ThreeLevelAreaWindow(getActivity()) {
                        @Override
                        protected void provinceClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.provinceClick(baseAreaEntity, position);
                            pickResultProvince.setNo(baseAreaEntity.getNo());
                            pickResultProvince.setName(baseAreaEntity.getSimpleName());
                            if (getString(R.string.app_all).equals(baseAreaEntity.getSimpleName()) || pickResultProvince.getName().equals(baseAreaEntity.getSimpleName())) {
                                pickResultCity.setNo("");
                                pickResultCity.setName("");
                                pickResultArea.setNo("");
                                pickResultArea.setName("");
                            }
                        }

                        @Override
                        protected void cityClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.cityClick(baseAreaEntity, position);
                            pickResultCity.setNo(baseAreaEntity.getNo());
                            pickResultCity.setName(baseAreaEntity.getSimpleName());
                            if (getString(R.string.app_all).equals(baseAreaEntity.getSimpleName()) || pickResultCity.getName().equals(baseAreaEntity.getSimpleName())) {
                                pickResultArea.setNo("");
                                pickResultArea.setName("");
                            }
                        }

                        @Override
                        protected void areaClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.areaClick(baseAreaEntity, position);
                            pickResultArea.setNo(baseAreaEntity.getNo());
                            pickResultArea.setName(baseAreaEntity.getSimpleName());
                        }

                        @Override
                        protected void reset() {
                            super.reset();
                            pickResultProvince.clear();
                            pickResultCity.clear();
                            pickResultArea.clear();
                            binding.sct.contentSelect("全部",true,false,binding.sct.getSize() == 2 ? 1 : 0);
                            popCity.dismiss();
                            initFilterData(false);
                        }
                    };
                    popCity.setBgView(binding.grayLayout);
                    popCity.setShowSimpleName(true);
                    popCity.setProvinceSingle();
                    popCity.setCitySingle();
                    popCity.setAreaSingle();
                    pickResultProvince.setName(mAreaName);
                    popCity.setOnResultClick((key1, key2, key3) -> {
                        initFilterData(false);
                        if (!getString(R.string.app_all).equals(pickResultArea.getName()) && !"".equals(pickResultArea.getName())) {
                            binding.sct.contentSelect(pickResultArea.getName(),true,false,binding.sct.getSize() == 2 ? 1 : 0);
                            return;
                        } else {
                            binding.sct.contentSelect(pickResultCity.getName(),true,false,binding.sct.getSize() == 2 ? 1 : 0);
                        }

                        if (!getString(R.string.app_all).equals(pickResultCity.getName()) && !"".equals(pickResultCity.getName())) {
                            binding.sct.contentSelect(pickResultCity.getName(),true,false,binding.sct.getSize() == 2 ? 1 : 0);
                            return;
                        } else {
                            binding.sct.contentSelect(pickResultProvince.getName(),true,false,binding.sct.getSize() == 2 ? 1 : 0);
                        }

                        if (!getString(R.string.app_all).equals(pickResultProvince.getName()) && !"".equals(pickResultProvince.getName())) {
                            binding.sct.contentSelect(pickResultProvince.getName(),true,false,binding.sct.getSize() == 2 ? 1 : 0);
                        } else {
                            binding.sct.contentSelect("全部",true,false,binding.sct.getSize() == 2 ? 1 : 0);
                        }
                    });
                    popCity.setOnDismissListener(() -> binding.sct.contentSelect(!"地区".equals(binding.sct.getName(binding.sct.getSize() == 2 ? 1 : 0)),false,binding.sct.getSize() == 2 ? 1 : 0));

                    popCity.setDataForAll(addressEntities, true, mAreaCode);
                }
            }
        });
    }

    @Override
    protected void onLazyLoad() {
        pickResultProvince.setNo(mAreaCode);

        binding.sct.contentSelect(mAreaName,true,false,1);

        initFilterData(false);
        viewModel.getCityList();
        viewModel.getCategoryType();
    }

    @Override
    public void onMultiClick(View v) {
        super.onMultiClick(v);
        int id = v.getId();
        if (id == R.id.iv_employment_all) {
            if (carsTypeData != null && carsTypeData.size() > 0) {
                carsTypePopWindow.setData(carsTypeData, typePosition);
                carsTypePopWindow.showPopwindow(binding.ivEmploymentAll, 0, 0);
            }
            binding.ivEmploymentAll.setImageResource(R.mipmap.btn_expand_up_gray);
        }
    }

    private void showType() {
        binding.sct.contentSelect(true,false,0);
        popMajor.showPopwindow0(binding.sct);
    }

    /**
     * 省市区pop
     */
    public void showCityPop() {
        binding.sct.contentSelect(true,false,binding.sct.getSize() == 2 ? 1 : 0);
        popCity.showPopwindow(binding.sct, 0, 0);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (NumberConstant.sIsBackForTeam == 1) {
            initFilterData(false);
            NumberConstant.sIsBackForTeam = 0;
        }
    }

    private void setTextButton(){
        selectPopEntity0 = new SelectPopEntity("工程专项", "1", false, true);
        SelectPopEntity selectPopEntity1 = new SelectPopEntity("地区", "2", false, true);
        binding.sct.addTextButton(selectPopEntity0);
        binding.sct.addTextButton(selectPopEntity1);
    }
}
